package Controller;

import Model.Orders;
import DataAccess.util.JsfUtil;
import DataAccess.util.PaginationHelper;
import DataAccess.OrdersFacade;
import Model.Category;
import Model.Customer;
import Model.Orderproducts;
import Model.Products;
import Model.User;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

@ManagedBean(name = "ordersController")
@SessionScoped
public class OrdersController implements Serializable {

    private Orders current;
    private DataModel items = null;
    @EJB
    private DataAccess.OrdersFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    EntityManager entityManager = Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();

    public OrdersController() {
    }

    public Orders getSelected() {
        if (current == null) {
            current = new Orders();
            selectedItemIndex = -1;
        }
        return current;
    }

    private OrdersFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Orders) getItems().getRowData();
        
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Orders();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            LastID la = new LastID();
            int i = la.LastID("Orders");
            current.setId(i);
            Date d = new Date();
            current.setCreateddate(d);
            getFacade().create(current);
            JsfUtil.addSuccessMessage("Başarıyla oluşturuldu");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Hata oluştu");
            return null;
        }
    }
    private String createStatus;

    public void createForOrderPage() {
        try {
            getSelected().setCustomerid(getUser().getId());
            LastID la = new LastID();
            int i = la.LastID("Orders");
            current.setId(i);//şuan order oluşuyor.
            Date d = new Date();
            current.setCreateddate(d);
            getFacade().create(current);
            int j = la.LastID("Orderproducts");
            Timestamp time = getCurrentTimeStamp(d);
            String querystring = "INSERT INTO Orderproducts(id,orderid,productid,price,orderdate) Values("+j+","+i+","+getProduct().getId()+","+getProduct().getPrice()+",'"+null+"')";
            Query query = entityManager.createNativeQuery(querystring);
            query.executeUpdate();
            createStatus = "orderSuccess";
        } catch (IllegalArgumentException e) {
            createStatus = "orderError";
        }
    }
 private static java.sql.Timestamp getCurrentTimeStamp(Date today) {
 
	
	return new java.sql.Timestamp(today.getTime());
 
}
    public String goToStatusPage() {
        return createStatus;
    }

    public Customer getUser() {
        Customer customer = new Customer();
        Map<String, Object> session = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        User user = (User) session.get("user");
        String username = (String) user.getUsername();

        Query query = entityManager.createNamedQuery("Customer.findByCustomerUsername");
        query.setParameter("username", username);
        List<Customer> customerList = (List<Customer>) query.getResultList();
        customer = customerList.get(0);
        return customer;
    }

    public Products getProduct() {
        Query query = entityManager.createNamedQuery("Products.findById");
        query.setParameter("id", Integer.parseInt(getParametresForProduct()));
        List<Products> products = (List<Products>) query.getResultList();
        return products.get(0);
    }

    public String getParametresForProduct() {
        Object req = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String productId = ((HttpServletRequest) req).getParameter("productId");
        return "2";
    }

    public String prepareEdit() {
        current = (Orders) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Güncellendi");
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Hata oluştu");
            return null;
        }
    }

    public String destroy() {
        current = (Orders) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage("Silindi");
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Hata oluştu");
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Customer getCustomer() {
        EntityManager entityManager = Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager.createNamedQuery("Customer.findById");
        query.setParameter("id", current.getId());
        Customer customer = new Customer();
        customer = (Customer) query.getSingleResult();
        return customer;
    }

    @FacesConverter(forClass = Orders.class)
    public static class OrdersControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            OrdersController controller = (OrdersController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "ordersController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Orders) {
                Orders o = (Orders) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Orders.class.getName());
            }
        }
    }
}
